package microarray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable
public class EFetch extends EUtil implements Serializable{


	/**
	 * 
	 */
	private static final long serialVersionUID = -1440519894092884842L;
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	
	@Persistent
	LinkedList<DataSeries> dataSeries;
	
	
	
	
	public EFetch(String queryKey, String webEnv) throws Exception 
	{
		dataSeries = new LinkedList<DataSeries>();
		

    	Map<String, String> params = new TreeMap<String, String>();
    	params.put("report", "docsum");
    	params.put("mode","text");
    	params.put("WebEnv", webEnv);
    	params.put("query_key", queryKey);
    	
    	
    	String baseURL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?";
    	InputStream bin = openInput(baseURL, params);
    	parseData(bin);
	}
	
	public void parseData(InputStream in) throws Exception
	{
		BufferedReader r = new BufferedReader(new InputStreamReader(in));
		String line;
		StringTokenizer tok;
		
		DataSeries currentSeries = null;
		while ((line = r.readLine()) != null)
		{
			tok = new StringTokenizer(line);
			while (tok.hasMoreTokens())
			{
				
				String token = tok.nextToken();
				if (token.length() > 3)
				{ 
					if (token.substring(0, 3).equals("GSE") || token.substring(0, 3).equals("GDS")){
						if (currentSeries != null)
							dataSeries.add(currentSeries);
						currentSeries = new DataSeries(token);
					}	
					if (token.substring(0, 3).equals("GSM"))
						currentSeries.addSample(token);
					if (token.substring(0, 3).equals("GPL"))
						currentSeries.setPlatform(token);
				}
			}
		}
		
	}
	
	public String toString()
	{
		String out = "GSE: ";
		for (DataSeries series: dataSeries)
			out += series + "\n";

		return out;
	}

}
